package com.digitalxpert.jargle.itext.rtf;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.SAXParseException;
import com.digitalxpert.jargle.sgtable.FlexibleTable;
import com.lowagie.text.Cell;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Image;
import com.lowagie.text.PageSize;
import com.lowagie.text.Phrase;
import com.lowagie.text.Table;
import com.lowagie.text.html.HtmlTagMap;
import com.lowagie.text.rtf.RtfWriter2;
import com.lowagie.text.rtf.headerfooter.RtfHeaderFooter;
import com.lowagie.text.xml.SAXmyHandler;

public class CardReportBuilder {
    private FlexibleTable table;
    private RtfWriter2 writer;
    private final int HEADER_ROW_COUNT = 1;
    Document document;

    public CardReportBuilder(FlexibleTable table) {
        this.table = table;
    }

    public void buildDocumentRTF() {
        try {
            document = new Document(PageSize.A4, 50, 50, 70, 70);
            writer = RtfWriter2.getInstance(document, new FileOutputStream("HelloWorld.rtf"));
            // HtmlParser.parse(document, new ByteArrayInputStream(new
            // String("<html><b>Stas
            // powel gulyat</b></html>").getBytes()),
            // new HtmlTagMap());
            document.open();
            parseHtml();
            System.out.println("4ik");
            writer.add(new Phrase("+++++++Stas123++++++++"));
            document.add(buildTableTabReport());
            writer.add(new Phrase("+++++++++++++++++++\n"));
            writer.add(new Phrase("+++++++Stas++++++++"));
            writer.add(new Phrase("+++++++++++++++++++"));
            setHeaderAndFooter();
            document.close();
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
    }

    private void parseHtml() {
        String text = "<html><head></head><body><table cellpadding='0' cellspacing='0' align='left' bordercolor='#000000' width='100%' border='0'><tr><td align='left'><b>fsfsdl dsf sdf вапвап ваыва:</b></td><td align='left'>-</td></tr><tr bgcolor='bgColor'><td align='left'><b>&#1055;&#1086;&#1083;&#1085;&#1086;&#1077; &#1085;&#1072;&#1080;&#1084;&#1077;&#1085;&#1086;&#1074;&#1072;&#1085;&#1080;&#1077;:</b></td><td align='left'>DigitalXpert</td></tr><tr bgcolor='bgColor'><td align='left'><b>&#1050;&#1086;&#1088;&#1086;&#1090;&#1082;&#1086;&#1077; &#1085;&#1072;&#1080;&#1084;&#1077;&#1085;&#1086;&#1074;&#1072;&#1085;&#1080;&#1077;:</b></td><td align='left'>DX</td></tr><tr bgcolor='bgColor'><td align='left'><b>&#1054;&#1043;&#1056;&#1053;:</b></td><td align='left'>12334234, 10-03-2005</td></tr><tr bgcolor='bgColor'><td align='left'><b>&#1048;&#1053;&#1053;:</b></td><td align='left'>75656657556, 04-07-2006</td></tr><tr bgcolor='bgColor'><td align='left'><b>&#1050;&#1055;&#1055;:</b></td><td align='left'>3454345, 03-06-2005</td></tr><tr bgcolor='bgColor'><td align='left'><b>&#1044;&#1077;&#1088;&#1078;&#1072;&#1090;&#1077;&#1083;&#1100; &#1088;&#1077;&#1077;&#1089;&#1090;&#1088;&#1072; &#1072;&#1082;&#1094;&#1080;&#1086;&#1085;&#1077;&#1088;&#1086;&#1074;:</b></td><td align='left'>-, -</td></tr><tr bgcolor='bgColor'><td align='left'><b>&#1071;&#1074;&#1083;&#1103;&#1077;&#1090;&#1089;&#1103; &#1091;&#1087;&#1088;&#1072;&#1074;&#1083;&#1103;&#1102;&#1097;&#1077;&#1081; &#1082;&#1086;&#1084;&#1087;&#1072;&#1085;&#1080;&#1077;&#1081;:</b></td><td align='left'>-</td></tr><tr bgcolor='bgColor'><td align='left'><b>&#1040;&#1082;&#1090;&#1091;&#1072;&#1083;&#1100;&#1085;&#1086; &#1085;&#1072;:</b></td><td align='left'>01-06-2007</td></tr></table></body></html>";
        try {
            SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
            SAXmyHandler handler = new SAXmyHandler(document, new HtmlTagMap());
            handler.setControlOpenClose(false);
            parser.parse(new ByteArrayInputStream(text.getBytes("utf8")), handler);
        } catch (SAXParseException e) {
            e.printStackTrace();
            Phrase ph = new Phrase(text);
            try {
                document.add(ph);
            } catch (DocumentException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private Table buildTableTabReport() {
        int columnCount = table.getColumnCount();
        int rowCount = table.getRowCount() + HEADER_ROW_COUNT;
        Table t = null;
        try {
            t = new Table(columnCount, rowCount);
            Cell cell = new Cell();
            cell.setBackgroundColor(Color.GRAY);
            for (int header = 0; header < columnCount; header++) {
                String name = table.getColumnName(header);
                Element element = new Phrase(name);
                cell = new Cell();
                cell.setBackgroundColor(Color.GRAY);
                cell.addElement(element);
                t.addCell(cell, 0, header);
            }
            for (int row = HEADER_ROW_COUNT; row < rowCount; row++) {
                for (int column = 0; column < columnCount; column++) {
                    Object cellData = table.getModel().getValueAt(row - HEADER_ROW_COUNT, column);
                    Element element = new Phrase("");
                    if (column == 0) {
                        ImageIcon icon = new ImageIcon("images/add.gif");
                        element = Image.getInstance(imageIconToByteArray(icon));
                        // element = Image.getInstance("images/Address.png");
                        System.out.println(element.toString());
                    } else {
                        element = new Phrase(cellData.toString());
                    }
                    Cell c = new Cell();
                    c.addElement(element);
                    t.addCell(c, row, column);
                }
            }
        } catch (Exception e) {
            System.out.println(e.toString());
        }
        return t;
    }

    private byte[] imageIconToByteArray(ImageIcon icon) {
        BufferedImage bi = new BufferedImage(icon.getImage().getWidth(null), icon.getImage().getHeight(null), BufferedImage.TYPE_INT_RGB);
        Graphics g = bi.createGraphics();
        g.drawImage(icon.getImage(), 0, 0, null);
        g.dispose();
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        try {
            ImageIO.write(bi, "png", stream);
        } catch (IOException ex1) {
        }
        return stream.toByteArray();
    }

    private void setHeaderAndFooter() {
        Phrase ph = new Phrase("Stas");
        RtfHeaderFooter hf = new RtfHeaderFooter(ph);
        hf.setAlignment(Element.ALIGN_CENTER);
        writer.setHeader(hf);
        Phrase ph2 = new Phrase("powel gulyat");
        hf = new RtfHeaderFooter(ph2);
        writer.setFooter(hf);
    }
}
